import React, { useMemo, useState, useRef } from 'react';
import bgImg from '@/assets/img/common/bg23.png'
import ipImg from '@/assets/img/ask/ip.png'
import askImg from '@/assets/img/common/ask.png'
import warnImg from '@/assets/img/ask/warin.png'
import ananImg from '@/assets/img/ask2/anan.png'
import listImg from '@/assets/img/ask2/list.png'
import bg1CenterImg from '@/assets/img/ask2/bg-1-center.png'
import { toolsList, Tool } from './const'
import ChatFooter from '@/components/ChatFooter'
import ChatContainer  from './chat'
import { authorization, chatID } from '@/constants/chat'
import useStore from '@/store'
import { useFetchQuestionList, useVoiceAssistant, useVoiceRecognition } from './hooks';
import { useStreamMessage } from '@/hooks/use-stream-message';
import { Spin, Switch, message } from 'antd';
// import DebugPanel from './debug-panel';
// import StreamTest from './stream-test';
import './index.less'
import api from '@/utils/api';
import chatService from '@/services/chat-service';
import VoiceMessage from './VoiceMessage';
import { MsgDrawer } from '@/components/message-list-drawer';
import { useClickMsgDrawer } from '@/components/message-list-drawer/hooks';

// 开发时导入测试函数
if (process.env.NODE_ENV === 'development') {
  // import('@/utils/stream-parser-test').then(module => {
  //   module.testStreamParser();
  // });
  
  // // 导入语音识别测试工具
  // import('@/utils/voice-test-utils').then(() => {
  //   console.log('🎤 语音识别测试工具已加载');
  // });
}

// 导入语音测试组件
// import VoiceTest from './voice-test';


// 使用 Tailwind 类代替内联样式

interface Message {
  id: number;
  content: string;
  role: string;
  isStreaming?: boolean;
}

const Talk: React.FC = () => {
  const sessionId = useStore((state) => state.chatSession.sessionId);
  const {questionList} = useFetchQuestionList();
  const {chatSession, setChatSession} = useStore();
  const [isSending, setIsSending] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [isVoiceInput, setIsVoiceInput] = useState(false);
    const { visible, hideModal, showModal } = useClickMsgDrawer();
  // 使用语音助手钩子，替代原来的状态管理
  const { isEnabled: aiEnabled, toggleVoiceAssistant, startRecognize } = useVoiceAssistant();
  
  // 当前正在流式传输的消息ID
  const [streamingMessageId, setStreamingMessageId] = useState<number | null>(null);
  // 用于跟踪聊天列表的引用
  const chatListRef = useRef<any[]>([]);
  
  // 使用流式消息 hook
  const { sendStreamMessage } = useStreamMessage({
    onStreamStart: () => {
      console.log('🚀 开始流式传输');
    },
    onMessageReceived: (content: string, isComplete: boolean) => {
      console.log('📨 接收到消息:', {
        content: content.substring(0, 100) + '...',
        isComplete,
        streamingMessageId,
        currentChatListLength: chatSession.chatList?.length
      });
      
      if (streamingMessageId !== null) {
        // 更新正在流式传输的消息内容
        const updatedChatList = (chatSession.chatList || []).map((msg: any) => {
          if (msg.id === streamingMessageId) {
            console.log('✅ 更新消息ID:', streamingMessageId, '内容长度:', content.length);
            return { ...msg, content, isStreaming: !isComplete };
          }
          return msg;
        });
        
        console.log('📝 更新后的聊天列表长度:', updatedChatList.length);
        setChatSession({ chatList: updatedChatList });
      } else {
        console.warn('⚠️ streamingMessageId 为 null，无法更新消息');
      }
    },
    onStreamEnd: () => {
      console.log('✅ 流式传输完成');
      setStreamingMessageId(null);
      setIsSending(false);
    },
    onError: (error) => {
      console.error('❌ 流式传输错误:', error);
      message.error('发送消息失败，请重试');
      setStreamingMessageId(null);
      setIsSending(false);
    },
  });
  

  // 处理发送消息
  const handleSendMessage = async (message: string) => {
    if (!message.trim() || isSending) return;

    console.log('🎯 开始发送消息:', message);
    setIsSending(true);
    
    // 添加用户消息
    const newUserMessage: Message = {
      id: Math.random(),
      content: message,
      role: 'user',
    };
    
    // 创建助手消息占位符
    const assistantMessageId = Math.random();
    const newAssistantMessage: Message = {
      id: assistantMessageId,
      content: '',
      role: 'assistant',
      isStreaming: true,
    };
    
    console.log('🆔 助手消息ID:', assistantMessageId);
    
    // 设置当前流式传输的消息ID
    setStreamingMessageId(assistantMessageId);
    
    // 先插入用户消息和空的助手消息
    const newChatList = [...(chatSession.chatList || []), newUserMessage, newAssistantMessage];
    console.log('📋 更新聊天列表，新长度:', newChatList.length);
    
    // 更新引用和状态
    chatListRef.current = newChatList;
    setChatSession({
      chatList: newChatList,
    });

    try {
      // 直接使用测试中成功的流式处理逻辑
      
      // const response = await fetch('https://ai.hzailab.cn/v1/conversation/completion', {
      //   method: 'POST',
      //   headers: {
      //     'Content-Type': 'application/json',
      //     'Authorization': 'IjlkMDZiNTY0NTU4YzExZjA5YTA0MGUxNjIxNWM4NjI0Ig.aGJLXg.PoZdZE8MPBx2SmrPjKha4V9sQLE',
      //   },
      //   body: JSON.stringify({
      //     "conversation_id": "318a616a46a911f0b84616f96a0dee16",
      //     "messages": [
      //       {
      //         "content": "你好！ 我是你的助理，有什么可以帮到你的吗？",
      //         "id": "9bd30aa9-7b0a-419d-aa40-cb1bfb34e085",
      //         "role": "assistant"
      //       },
      //       {
      //         "id": "user-message-" + Date.now(),
      //         "content": message,
      //         "role": "user",
      //         "doc_ids": []
      //       }
      //     ]
      //   }),
      // });
      const response = await fetch(api.sendChat, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'IjlkMDZiNTY0NTU4YzExZjA5YTA0MGUxNjIxNWM4NjI0Ig.aGJLXg.PoZdZE8MPBx2SmrPjKha4V9sQLE',
        },
        body: JSON.stringify({
          authorization,
          chatId: chatID,
          requestBody: {
            question: message,
            stream: 1,
            sessionId,
          }
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法获取响应流');
      }

      let buffer = '';
      let latestContent = '';
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        
        if (done) {
          console.log('✅ 流式响应完成');
          break;
        }

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
        
        // 处理缓冲区中的完整行
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';
        
        for (const line of lines) {
          if (!line.trim() || !line.startsWith('data:')) {
            continue;
          }
          
          const jsonStr = line.substring(5).trim();
          if (!jsonStr) {
            continue;
          }
          
          try {
            const parsed = JSON.parse(jsonStr);
            console.log('📨 主聊天解析到数据:', parsed);
            
            if (parsed.data) {
              // console.log('✅ 主聊天更新内容:', currentAnswer.substring(0, 100) + '...');
              let reference:any = {}
              if(parsed.getsecondcode){ // 获取流式输出后的第二段数据
                try {
                  const res =  await chatService.getSecondData({SecondDataCode:parsed.getsecondcode})
                  console.log('res', res)
                  reference = res?.data.data.data
                } catch (e) {
                  console.warn('获取文件失败:', e);
                }
              }
              console.log('获取到的reference', reference)
              const currentAnswer = parsed.getsecondcode? reference.answer : parsed.data.answer;
              latestContent = currentAnswer; // 保存最新内容
              // 立即更新助手消息内容
              chatListRef.current = chatListRef.current.map((msg: any) => {
                if (msg.id === assistantMessageId) {
                  console.log('🔄 更新消息ID:', assistantMessageId,);
                  return { 
                    ...msg, 
                    content: currentAnswer, 
                    isStreaming: true,
                    timestamp: Date.now(),
                    ...reference,
                  };
                }
                return msg;
              });
              
              console.log('📝 聊天列表已更新，消息数量:', chatListRef.current.length);
              setChatSession({ chatList: [...chatListRef.current] });
            }
          } catch (e) {
            console.warn('❌ 主聊天JSON解析失败:', jsonStr.substring(0, 50) + '...', e);
          }
        }
      }

      // 流式传输完成，移除 isStreaming 标记
      console.log('🏁 流式传输完成，最终更新状态');
      const finalChatList = chatListRef.current.map((msg: any) => {
        if (msg.id === assistantMessageId) {
          console.log('🎯 最终消息内容长度:', msg.content?.length);
          return { ...msg, isStreaming: false, timestamp: Date.now() };
        }
        return msg;
      });
      console.log('finalChatList', finalChatList)
      chatListRef.current = finalChatList;
      setChatSession({ chatList: [...finalChatList] });

    } catch (error) {
      console.error('❌ 发送消息失败:', error);
      
      // 移除添加的消息
      setChatSession({
        chatList: chatSession.chatList || [],
      });
    } finally {
      setStreamingMessageId(null);
      setIsSending(false);
    }
  };
  // 使用语音识别钩子，将识别到的文字展示在输入框中
  useVoiceRecognition((recognizedText, type) => {
    console.log('recognizedText', recognizedText);
    console.log('type', type);
    
    if(!isVoiceInput) {
       // 直接发送识别到的文字
       handleSendMessage(recognizedText);
    } else {
      // 写入输入框
      setInputValue(recognizedText);
      setIsVoiceInput(false);
      // handleSendMessage(recognizedText);
    }
   
  });
  const [showVoice, setShowVoice] = useState(false);
  // 处理语音按钮点击
  const handleVoiceClick = async () => {
    console.log('isEnabled', aiEnabled)
    if(!aiEnabled) {
      // console.log('语音助手未开启');
      message.error('请先开启语音助手');
      return
    }
    // 和app交互，唤起app测的语音识别
    try {
      setShowVoice(true)
      setIsVoiceInput(false);
      startRecognize()
    } catch (error) {
      console.error('语音输入失败:', error);
    }
  };

  // 处理添加按钮点击 输入文本
  const handleAddClick = () => {
    // message.warning('该功能暂未开放');
    // console.log('添加按钮被点击');
    startRecognize();
    setIsVoiceInput(true);
  };

  // 当前选择的对话类型
  const [sessionIdIndex, setSessionIdIndex] = useState(0);

  // 处理工具点击
  const handleToolClick = async (tool: Tool) => {
    if(tool.name === "智慧写作") {
      message.warning('该功能暂未开放');
      return
    }
    setChatSession({ chatList: [] });
    console.log('工具被点击:', tool);
    setSessionIdIndex(tool.id === 1?tool.id - 1:tool.id - 2)
  };
  // 开启语音助手
  const handleSwitchChange = () => {
    toggleVoiceAssistant(); // 如果没有成功，则switch开关状态不变
    
  };

  // 用 useMemo 包裹
  const questionCards = useMemo(() => (
    questionList.map((q, idx) => (
      // 最后一个mb 0
      <div key={idx} className={`flex items-center justify-between h-[48px] px-[24px] bg-white rounded-[28px] ${idx === questionList.length - 1 ? 'mb-0' : 'mb-[12px]'} `}>
        <span className="text-[#464646] text-[18px] ">{q.umQuestion}</span>
        {/* <img src={rightImg} className="h-3" alt="right" /> */}
      </div>
    ))
  ), [questionList]);
  // 发送语音
  const handleSend = (content: string, isVoice?: boolean) => {
    console.log(`发送${isVoice ? '语音' : '文字'}:`, content);
    setInputValue(content);
    // 这里可以调用API发送消息
  };

  // 打开消息列表抽屉
  const showMsgDrawer = () => {
    getSessionNameList()
    showModal();
  }

  const viocShowInputText = (show: boolean) => {
    setShowVoice(show)
  }
  const [msgHistory, setMsgHistory] = useState([]);
  // 会话名称列表
  const getSessionNameList = async () => {
    // const res = await chatService.getSessionNameList();
    const { data: sessionList } = await chatService.getSessionHistoryRecordList({
            sessionId,
            chatId: chatID,
            itemNum:-20
          });
    console.log('getSessionNameList', sessionList)
    setMsgHistory(sessionList.data || []);
  }
  // 点击会话列表内容，重新发送内容
  const handleMsgListItem = (content: string) => {
    // console.log('handleMsgListItem', content)
    // 写入输入框
    setInputValue(content);
    setIsVoiceInput(false);
    hideModal() //关闭抽屉
  }
  
  return (
    // 背景图是 /src/assets/img/login/bg23.png    
     
    <div 
    className={`bg-cover bg-center bg-no-repeat  w-screen flex flex-col items-center justify-start relative pb-32 pt-1 md:pt-6}`}
    style={{ backgroundImage: `url(${bgImg})` }}>
      {showVoice && <div className="fixed-bg-back">
        <VoiceMessage onSend={handleSend} showInputText={viocShowInputText} />
        {/* <div  className="cancle-bg">
          <div className='cancle-btn' onClick={() => {setShowVoice(false)}}>取消</div>
        </div> */}
        </div>}
        {/* 聊天列表 */}
        <MsgDrawer visible={visible} MsgList={msgHistory} activeIndex={0} hideModal={hideModal}
         handleMsgListItem={handleMsgListItem}  />
      {/* 开发环境下显示调试面板 */}
          {process.env.NODE_ENV === 'development' && (
            <>
              {/* <DebugPanel /> */ }
              {/* 暂时隐藏测试组件 */}
              {/* <div style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', zIndex: 10000 }}>
                <StreamTest />
              </div> */}
              
              {/* 语音识别测试组件 */}
              {/* <div style={{ position: 'fixed', top: '10px', right: '10px', zIndex: 10000, maxWidth: '400px', maxHeight: '80vh', overflow: 'auto' }}>
                <VoiceTest 
                  onRecognizeResult={(text, type) => {
                    console.log('🎯 测试组件收到识别结果:', { text, type });
                    // 这里可以测试你的语音识别回调是否正常工作
                    if (type === 'recognize') {
                      // 模拟直接发送消息
                      handleSendMessage(text);
                    }
                  }}
                />
              </div> */}
            </>
          )}
       {/* 顶部栏 吸顶 */}
      <div className="px-4 py-2 md:py-6 flex items-center justify-between sticky top-1 h-14 md:h-24 z-50 w-full">
        {/* 左侧留白区域 */}
        <div className="w-[48px] h-[48px] flex items-center justify-center">
          {/* 可选的回去按钮或其他功能按钮 */}
          <img src={listImg} alt="" className="w-[22px] h-[20px] " loading="lazy" onClick={showMsgDrawer} />
        </div>
        {/* 中间标题 */}
        <div className="absolute left-1/2 transform -translate-x-1/2">
          <span className="text-[16px] text-[#191919] font-medium">AI对话</span>
        </div>
        {/* 右侧控制区 */}
        <div className="flex items-baseline gap-2">
          {/* Ant Design Switch 组件 */}
          <div className="flex items-center gap-2">
            <Switch 
              checked={aiEnabled} 
              onChange={handleSwitchChange}
              className="mr-1"
            />
            {/* 指定的图标 */}
            <img src={ananImg} alt="头像" className="w-[27px] h-[27px] rounded-full" loading="lazy" />
          </div>
        </div>
      </div>
      {/* 滚动条样式调整。变细写 */}
      <div className="w-full overflow-y-auto overflow-x-hidden pb-20 px-4 md:px-5">
     
      {/* 欢迎与吉祥物 */}
      {/* width: 100%;
      height: 218px;
      background-image: linear-gradient(90deg, #B5FFF6 0%, #ffeab9e0 13%, #ffc0cfbd 31%, #ebc9ff9e 59%, #CCDEFE 100%);
      border-radius: 28px; 用tailwind.css */}

      <div style={{
        backgroundImage: 'linear-gradient(90deg, #B5FFF6 0%, #ffeab9e0 13%, #ffc0cfbd 31%, #ebc9ff9e 59%, #CCDEFE 100%)',
      }} className="w-full h-[218px] rounded-[28px]  flex flex-col items-center mt-[40px]  relative">
        <div className="absolute left-[24px] top-[-40px] flex items-center justify-center z-20">
          <img src={ipImg} alt="吉祥物" className="w-[120px] h-[120px]" loading="lazy"/>
        </div>
        {/* 宽度撑满父容器宽度 */}
        <div className="font-bold text-[#3F81F3] flex flex-row items-center mt-[20px]  text-center w-full left-20 pl-[144px]">
          <div className="flex items-center justify-center">
            <span className="text-[18px] font-['YouSheShaYuFeiTeJianKangTi'] text-[#191919] font-bold ">Hi~</span>
          </div>
          <div>
            <span className="text-[18px] font-['YouSheShaYuFeiTeJianKangTi'] text-[#001E69] font-bold leading-tight">我是实验室生物安全小助理，很高兴为您服务!</span>
          </div>
        </div>
      </div>
      {/* 猜你想问卡片区 */}
      {/* 猜你想问卡片区 */}
      <div className="relative min-h-[200px] w-full mt-[-146px] rounded-[28px]  p-[24px]  z-10 overflow-hidden">
        {/* 模糊背景层 背景图是bg1CenterImg */}
        <div 
          style={{
            backgroundImage: `url(${bg1CenterImg})`,
            backgroundSize: '100% 100%',
            backgroundRepeat: 'no-repeat',
            // filter: 'blur(20px)',
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            zIndex: -1,
            height: '100%',
          }} 
          className="rounded-[28px]"
        ></div>
        {/* 内容层 - 不会被模糊 */}
        <div className="flex items-center gap-1 mb-3 md:mb-[16px]">
          <img src={warnImg} className="w-[32px] h-[32px]" alt="waring" loading="lazy" />
          <img src={askImg} className="h-[27px]" alt="ask" loading="lazy"  />
        </div>
        <div>
          {questionCards}
        </div>
      </div>
      {/* 聊天区 */}
      <div className="w-full  mt-4 ">
        <ChatContainer controller={new AbortController()} sessionIdIndex={sessionIdIndex}   />
        {/* 流式传输状态指示 */}
        {isSending && (
          <div className="flex items-center justify-center p-4">
            <Spin size="small" />
            <span className="ml-2 text-gray-500">正在接收回复...</span>
          </div>
        )}
      </div>
      </div>
      
      {/* 底部输入栏和功能 置底 用tailwind.css来写 */}
      <div className="absolute bottom-0 left-[20px] right-[20px] z-[1000]  pb-4">
        <ChatFooter 
          toolsList={toolsList}
          onSendMessage={handleSendMessage}
          onVoiceClick={handleVoiceClick} 
          onAddClick={handleAddClick} // 和app 交互，唤起app测的 语音转文本，然后app测把文本回调给h5 input输入框
          onToolClick={handleToolClick}
          placeholder="很高兴为您解答"
          inputValue={inputValue}
        />
      </div>
    </div>
  );
};

export default Talk;



